package server

import (
	"errors"
	"fmt"
	"strconv"
	"week52/common/model/mysql"
	"week52/common/proto/class"
)

func AddClass(req *class.AddClassReq) (*class.AddClassResp, error) {
	c := mysql.Class{
		Name:    req.Name,
		Address: req.Address,
		Types:   int(req.Types),
		Price:   req.Price,
		Num:     int(req.Num),
	}
	err := c.Add()
	if err != nil {
		return nil, errors.New("预约失败")
	}
	return &class.AddClassResp{Success: c.Name + "预约成功"}, nil
}

func ClassDetail(req *class.ClassDetailReq) (*class.ClassDetailResp, error) {
	c := mysql.Class{}
	detail, err := c.Detail(int(req.Id))
	if err != nil {
		return nil, errors.New("查看失败")
	}

	var list []*class.Detail
	for _, cc := range detail {
		list = append(list, &class.Detail{
			Id:      int32(cc.ID),
			Name:    cc.Name,
			Address: cc.Address,
			Types:   int32(cc.Types),
			Num:     int32(cc.Num),
			Price:   cc.Price,
		})
	}
	return &class.ClassDetailResp{Detail: list}, nil
}

func AddClassOrder(req *class.AddClassOrderReq) (*class.AddClassOrderResp, error) {
	c := mysql.Class{}
	classes, err := c.FindClassId(int(req.ClassId))
	if err != nil {
		return nil, errors.New("没有该课程")
	}

	co := mysql.ClassOrder{
		ClassId: int(classes.ID),
		Name:    classes.Name,
		Dates:   req.Dates,
		Times:   req.Times,
		Address: classes.Address,
		Num:     classes.Num,
		Price:   classes.Price,
	}
	err = co.AddClassOrder()
	if err != nil {
		return nil, errors.New("预约失败")
	}

	return &class.AddClassOrderResp{Success: "预约成功"}, nil
}

func TrueOrder(req *class.TrueOrderReq) (*class.TrueOrderResp, error) {
	co := mysql.ClassOrder{}
	co.UpdatedWriters(req.Writers, int(req.Id))

	err := co.UpdatedWritersId(int(req.Id))
	if err != nil {
		return nil, errors.New("确认预约失败")
	}

	return &class.TrueOrderResp{Success: "确认预约"}, nil
}

func StatusOrderList(req *class.StatusOrderListReq) (*class.StatusOrderListResp, error) {
	co := mysql.ClassOrder{}
	finds, err := co.Finds(int(req.Status))
	if err != nil {
		return nil, errors.New("查找失败")
	}

	var lists []*class.OrderList
	for _, ccoo := range finds {
		lists = append(lists, &class.OrderList{
			Id:      int32(ccoo.ID),
			Name:    ccoo.Name,
			Dates:   ccoo.Dates,
			Times:   ccoo.Times,
			Address: ccoo.Address,
			Num:     int32(ccoo.Num),
			Price:   ccoo.Price,
			Writers: ccoo.Writers,
		})
	}

	return &class.StatusOrderListResp{List: lists}, nil
}

func TellSmall(req *class.TellSmallReq) (*class.TellSmallResp, error) {
	co := mysql.ClassOrder{}
	find, err := co.Find(int(req.Id))
	if err != nil {
		return nil, errors.New("未找到")
	}

	orderTime, _ := strconv.Atoi(find.Times)

	if orderTime < 30 {
		return nil, errors.New("课程倒计时小于30分钟")
	}

	if orderTime >= 60 {
		fmt.Println("用户在课程倒计时大于1小时时可进行取消预约")
		err = co.UpdatedStatus(int(req.Id))
		if err != nil {
			return nil, errors.New("预约取消失败")
		}
	}

	return &class.TellSmallResp{Success: "成功"}, nil
}
